package com.copa.l662;

import java.util.*;

/**
 * @author copa
 * @createDate 2022-07-07 09:08
 * @function BFS
 */
public class Test1 {

    public int widthOfBinaryTree(TreeNode root) {
        if (null == root) {
            return 0;
        }
        // 这个用来存储树的结点（当前高度）
        Queue<TreeNode> queue = new LinkedList<>();
        // 这个用来存储对应树的索引（当前高度）
        Queue<Integer> indexQueue = new LinkedList<>();
        queue.add(root);
        indexQueue.add(1);
        int result = 0;
        while (queue.size() > 0) {
            int size = queue.size();
            int start = indexQueue.peek();
            int end = start;
            while (size > 0) {
                TreeNode treeNode = queue.poll();
                Integer index = indexQueue.poll();
                end = index;
                if (null != treeNode.left) {
                    queue.add(treeNode.left);
                    // 左子树索引必然是 当前树索引 * 2
                    indexQueue.add(index * 2);
                }
                if (null != treeNode.right) {
                    queue.add(treeNode.right);
                    // 右子树索引必然是 当前树索引 * 2 + 1
                    indexQueue.add(index * 2 + 1);
                }
                size--;
            }
            result = Math.max(result, end - start + 1);
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(3);
        root.left.left = new TreeNode(5);
        root.left.right = new TreeNode(3);
        root.right = new TreeNode(2);
        root.right.right = new TreeNode(9);
        System.out.println(new Test1().widthOfBinaryTree(root));
    }
}
